<template>
  <div class="add-account">
    <el-dialog
      v-el-drag-dialog="{ drag: true, full: false, resize: true }"
      title="新增银行流水"
      :close-on-click-modal="false"
      :visible="true"
      @close="closeMd"
      width="40%"
      append-to-body>
      <el-form 
        :model="sourceData" 
        ref="formRef" 
        :label-width="'100px'">
        <el-form-item
          label="我的银行"
          prop="myBank"
          :rules="[ { required: true, message: '请选择我的银行', trigger: 'blur' } ]">
          <el-select
            @change="handleBalance"
            style="width: 100%"
            v-model="sourceData.myBank"
            placeholder="请选择我的银行">
            <el-option
              v-for="(item, i) in bankOptions"
              :key="i"
              :label="item.bankName"
              :value="item.bankName+'/'+item.cardNo"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="金额类型"
          prop="moneyType"
          :rules="[ { required: true, message: '请选择金额类型', trigger: 'blur' } ]">
          <el-select
            filterable
            style="width: 100%"
            v-model="sourceData.moneyType"
            placeholder="请选择金额类型">
            <el-option
              v-for="item in moneyOptions"
              :key="item.id"
              :label="item.typeName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="客户名称"
          prop="cusIds"
          :rules="[{ required: false, message: '请选择客户名称', trigger: 'blur' }]">
          <el-select
            filterable multiple
            collapse-tags
            remote reserve-keyword
            :remote-method="queryCusPageList"
            style="width: 100%"
            v-model="sourceData.cusIds"
            placeholder="请选择客户名称">
            <el-option
              v-for="(item, index) in cusOptions"
              :key="index"
              :label="item.unitName"
              :value="item.id"
              @click.native="selCusName(item)">
              <span>{{item.unitName}}</span>
              <span>{{item.baseUserId.realName+'（'+item.baseUserId.phone+'）'}}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="对方户名"
          prop="transName"
          :rules="[{ required: false, message: '请输入对方户名', trigger: 'blur' }]">
          <el-input
            style="width: 100%"
            placeholder="请输入对方户名"
            v-model="sourceData.transName">
          </el-input>
        </el-form-item>

        <el-form-item label="对方账号" prop="transNum">
          <el-input
            style="width: 100%"
            placeholder="请输入对方账号"
            v-model="sourceData.transNum">
          </el-input>
        </el-form-item>

        <el-form-item
          label="收支状态"
          prop="tradeStatus"
          :rules="[{ required: true, message: '请选择收支状态', trigger: 'blur' }]">
          <el-select
            v-model="sourceData.tradeStatus"
            placeholder="请选择收支状态"
            style="width: 100%"
            @change="handleBlur">
            <el-option label="收入" value="0"></el-option>
            <el-option label="支出" value="1"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="交易时间"
          prop="tradeTime"
          :rules="[{ required: true, message: '请选择交易时间', trigger: 'blur' }]">
          <el-date-picker
            v-model="sourceData.tradeTime"
            type="datetime"
            placeholder="交易日期"
            style="width: 100%"
            format="yyyy-MM-dd HH:mm"
            value-format="yyyy-MM-dd HH:mm"
          />
        </el-form-item>

        <el-form-item
          label="交易金额"
          prop="tradeMoney"
          :rules="[
            { required: true, message: '请选择交易金额', trigger: 'blur' },
            this.$rules.isFloat('交易金额必须大于0'),
          ]">
          <el-input
            @blur="handleBlur"
            maxlength="10"
            style="width: 100%"
            placeholder="请输入交易金额"
            v-model="sourceData.tradeMoney"
          />
        </el-form-item>

        <el-form-item label="余额" prop="balance">
          <el-input
            disabled
            maxlength="10"
            style="width: 100%"
            placeholder="请选择我的银行，自动查询余额"
            v-model="sourceData.balance">
          </el-input>
        </el-form-item>

        <el-form-item label="摘要" prop="remark">
          <el-input
            type="textarea"
            maxlength="500"
            placeholder="款项说明，字数限定500字"
            :autosize="{ minRows: 5, maxRows: 4 }"
            style="width: 100%"
            v-model="sourceData.remark">
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button
            icon="el-icon-circle-plus"
            type="primary"
            @click="onSubmit"
            :disabled="fm.sb.load">
            {{ fm.sb.text }}
          </el-button>
          <el-button icon="el-icon-error" @click="closeMd">关闭</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
// import { mapGetters } from "vuex";
import elDragDialog from "@/directive/el-drag-dialog";

import {
  addBankAccount,
  findBalanceByBankInfo,
} from "@/api/services/order.service";

import {
  getMoneyTypeDict,
  getBankListDict,
  queryComboCusPageList,
} from "@/api/services/common.service";

export default {
  name: "AddAccount",
  directives: { elDragDialog },
  props: ["state"],
  // computed: {
  //   ...mapGetters(["lunitNum", "uname"]),
  // },
  data() {
    return {
      sb: {
        load: false,
        text: "添加",
      },
      sourceData: {
        myBank: "", // 我的银行
        moneyType: "", //金额类型
        cusIds: [], // 客户id
        cusObjArr: [], // 客户名称
        transName: "", //对方户名
        transNum: "", //对方账号
        tradeStatus: "", // 收支状态
        tradeTime: "", // 交易时间
        tradeMoney: null, // 交易金额
        balance: "", // 余额
        balance2: "", // 余额
        remark: "", // 摘要
      },
      fm: {
        fname: "addAccountFm",
        sb: { load: false, text: "立即添加" },
      },
      moneyOptions: [],
      bankOptions: [],
      cusOptions: [],
    };
  },
  created() {
    if (this.datas) {
      let { id, bankName, cardName, cardNo } = this.datas;
      this.sourceData = {
        updId: id,
      };
    }
    this.getDict();
  },
  methods: {
    closeMd() {
      this.$emit("myClick", {true: false});
    },
    getDict() {
      getMoneyTypeDict().then((res) => {
        this.moneyOptions = res.mTypes;
      });
      getBankListDict().then((res) => {
        this.bankOptions = res.banks;
      });
    },
    // 获取-客户数据列表
    queryCusPageList(query) {
      let {cusObjArr} = this.sourceData;

      if (!query) return (this.cusOptions = []);

      queryComboCusPageList({ find: query }).then((res) => {
        if(res.code == 1) {
          this.cusOptions = res.data;

          // 追加已选中的数据
          if(cusObjArr.length > 0) this.cusOptions = cusObjArr.concat(this.cusOptions);
        }
      });
    },
    // 客户名称选择
    selCusName(obj){
      let that = this, {cusIds, cusObjArr} = that.sourceData;
      
      let index = cusObjArr.findIndex(it => it.id == obj.id);
      let is = cusIds.findIndex(it => it == obj.id);
      if(is != -1){// 存在，表示添加
        if(index == -1) cusObjArr.push(obj);
      }else{// 不存在，表示删除
        if(index != -1) cusObjArr.splice(index, 1);
      }
    },
    handleBlur() {
      // 0收入 1支出
      const { tradeStatus, balance2, tradeMoney } = this.sourceData;
      
      let result = 0;
      if (tradeStatus == 1) {
        result = Number(balance2) - Number(tradeMoney);
      } else {
        result = Number(tradeMoney) + Number(balance2);
      }
      this.sourceData.balance = result.toFixed(2);
    },
    handleBalance() {
      let ps = {
        bankName: this.sourceData.myBank.split('/')[0], // 银行名称
        bankNo: this.sourceData.myBank.split('/')[1], // 银行卡号
      };
      findBalanceByBankInfo(ps).then((res) => {
        if (res.code === 1) {
          this.sourceData.balance2 = res.balance;
        }else{
          this.sourceData.balance2 = 0;
        }
      });
    },
    
    // 提交-表单
    onSubmit() {
      const that = this, ps = that.U.scopy(this.sourceData);

      that.$refs.formRef.validate((valid) => {
        if (valid) {
          ps.tradeMoney = Number(ps.tradeMoney);

          if(ps.cusObjArr) {
            let arr = [];
            ps.cusObjArr.forEach(it => {
              arr.push(it.baseUserId.realName+','+it.baseUserId.phone);
            });
            ps.cusName = arr.join('/@');
          }
          delete ps.cusIds;
          delete ps.cusObjArr;
          
          console.log('银行记账提交前参数', ps);
          
          that.fm.sb.load = true; // 添加按钮禁用效果
          addBankAccount(ps).then((res) => {
            that.fm.sb.load = false; // 取消按钮禁用效果
            if (res.code === 1) {
              that.closeMd();
              that.$emit("reloadDg");
            }else if (res.code === 0) {
              that.U.qerror(res.msg);
            }
          });
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>
.typeSty {
  padding: 0 20px 0 20px;
  font-weight: 600;
}
</style>